package no.ntnu.fp.storage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBConnection {
	private Connection connection;
	private String mysqlDriver;
	private String url;
	
	public DBConnection() {
		this("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/systemutvikling");
	}
	
	public DBConnection(String mysqlDriver, String dbAddress) {	
		this.mysqlDriver = mysqlDriver;
		this.url = dbAddress;
		initializeDB();
	}
	
	private void initializeDB() {
		getClassForName(mysqlDriver);
		Properties props = new Properties();
		props.setProperty("user","bruker");
		props.setProperty("password","kalender");
		connection = getConnection(props);
	}
	
	private Connection getConnection(Properties props) {
		try {
			return DriverManager.getConnection(url, props);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	private void getClassForName(String mysqlDriver) {
		try {
			Class.forName(mysqlDriver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public ResultSet makeSingleQuery(String query) {
		Statement st;
		ResultSet rs;
		System.out.println("Query mottatt:" + query);
		try {
			st = connection.createStatement();
			rs = st.executeQuery(query);
			System.out.println("Query kjort:" + query);
			return rs;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	public int makeUpdate(String query) {
		Statement st;
		int res;
		System.out.println("update mottatt: " + query);
		try {
			st = connection.createStatement();
			res = st.executeUpdate(query);
			System.out.println("update kjort: " + query);
			return res;
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	public PreparedStatement preparedStatement(String sql) throws SQLException {
		return connection.prepareStatement(sql);
	}
	
	
	public void closeQuery(ResultSet rs) throws SQLException {
		if(rs.getStatement() != null)
			rs.getStatement().close();
		else
			rs.close();
	}
	
	public void closeConnection() throws SQLException {
		connection.close();
	}
}
